﻿using log4net;
using Quartz;
using Quartz.Spi;
using IScheduler = Quartz.IScheduler;

namespace JT809.GpsRedisConsumer
{
    public class QuartzStartup
    {
        private readonly ILog _logger;
        private readonly IConfiguration _configuration;
        private readonly ISchedulerFactory _schedulerFactory;
        private readonly IJobFactory _iocJobfactory;
        private IScheduler _scheduler;
        public QuartzStartup(IJobFactory iocJobfactory, ISchedulerFactory schedulerFactory, IConfiguration configuration)
        {
            _schedulerFactory = schedulerFactory;
            _iocJobfactory = iocJobfactory;
            _configuration = configuration;
            _logger = LogManager.GetLogger(LogHelper.Repository.Name, GetType().Name);
        }
        public async Task Start()
        {
            _logger.Info("========== ISchedulerFactory Start ==========");
            _logger.Info("---------- Initialization Complete ----------");

            _scheduler = await _schedulerFactory.GetScheduler();
            //替换默认工厂
            _scheduler.JobFactory = _iocJobfactory;

            // get a "nice round" time a few seconds in the future...
            DateTimeOffset startTime = DateBuilder.NextGivenSecondDate(null, 2);

            #region 在线监测接口-按要求10分钟一次
            var WithCronSchedule_job = !string.IsNullOrEmpty(_configuration["WithCronSchedule_job"]) ? _configuration["WithCronSchedule_job"].ToString() : "0 * * * * ?";
#if DEBUG
            WithCronSchedule_job = "0/10 * * * * ?";
#endif
            IJobDetail job = JobBuilder
                .Create<JobDetail>()
                .WithIdentity("job", "group")
                .Build();

            //创建一个触发器
            ICronTrigger trigger = (ICronTrigger)TriggerBuilder.Create()
                .WithIdentity("trigger", "group")
                .StartAt(startTime)
                .WithCronSchedule(WithCronSchedule_job)
                .Build();

            //job.JobDataMap.Put(JobDetail.startKey, true);
            DateTimeOffset? ft = await _scheduler.ScheduleJob(job, trigger);
            #endregion

            await _scheduler.Start();
#if DEBUG
            //测试时打开
            _logger.Info("---------- Waiting ten minutes... ----------");
            await Task.Delay(TimeSpan.FromMinutes(10));
            _logger.Info("---------- Shutting Down ----------");
            await _scheduler.Shutdown(true);
            _logger.Info("---------- Shutdown Complete ----------");
            SchedulerMetaData metaData = await _scheduler.GetMetaData();
            _logger.Info($"========== Executed {metaData.NumberOfJobsExecuted} jobs. ==========");
#endif
        }
        public void Stop()
        {
            if (_scheduler == null)
            {
                return;
            }

            if (_scheduler.Shutdown(waitForJobsToComplete: true).Wait(30000))
                _scheduler = null;
            else
            {
            }
            _logger.Info("========== Schedule job upload as application stopped ==========");
        }
    }
}
